<script lang="ts" setup>
import { computed, onMounted } from 'vue'
import { ref } from 'vue'
import { reactive } from 'vue'
import { Message } from '@arco-design/web-vue'
import GoodsCommentLabel from './components/GoodsCommentLabel.vue'
import { useRoute, useRouter } from 'vue-router'
import { getGoodsCommentListAPI, getGoodsItemAPI, getGoodsListAPI2, postGoodsCommentAPI } from '@/api/goods'
import type { GoodsItemType } from '@/types/goods'
import { addShoppingCartAPI } from '@/api/cart'
import { useAddressStore } from '@/stores/address'
import { storeToRefs } from 'pinia'
import { useCartStore } from '@/stores/cart'
import { useAuthStore } from '@/stores/auth'

const route = useRoute()
const baseURL = import.meta.env.VITE_BASE_URL
// 面包屑
const routes = reactive([
  {
    path: '/',
    label: '首页'
  }
])

// 图片列表
const imgList = ref<string[]>([])
// 商品海报图片
const posterList = ref<string[]>([])
// 商品详情
const goods = ref<GoodsItemType>({
  category: '',
  id: 0,
  name: '',
  price: 0,
  stock: 0
})

const QUERY_MAP: Record<string, string> = reactive({
  无暇底妆: '1',
  国风彩妆: '2',
  实力锁妆: '3',
  温和净卸: '4',
  匠心妆具: '5'
})

const getGoodsItem = async () => {
  goods.value = await getGoodsItemAPI(route.params.id)
  console.log(goods.value)

  // 通过商品的大分类，找到对应的编号
  routes.push({
    path: '/list/' + QUERY_MAP[goods.value.category],
    label: goods.value.category
  })

  routes.push({
    path: route.fullPath,
    label: goods.value.name
  })
  imgList.value = goods.value.images?.split(',').map((item: string) => baseURL + item)!
  posterList.value = goods.value.posters?.split(',').map((item: string) => baseURL + item)!
  console.log(imgList)
}

onMounted(() => getGoodsItem())

const productList = ref<GoodsItemType[]>([])
const recommendList = ref<GoodsItemType[]>([])

const index = ref(0)

// 获取推荐列表
const getRecommendList = () => {
  recommendList.value = productList.value.slice(index.value, index.value + 3)
  index.value += 3
  if (index.value + 3 >= productList.value.length) {
    index.value = 0
  }
}

// 获取商品列表
const getGoodsList = async () => {
  productList.value = await getGoodsListAPI2()
  getRecommendList()
}

onMounted(() => getGoodsList())

// 商品选项
const goodsOptions = reactive({
  lettering: false,
  wish: false,
  comment: false
})

// 刷新推荐列表
const handleRefreshRecommendList = () => {
  getGoodsList()
  Message.success({
    content: '更新列表成功!'
  })
}

// 评论列表
const commentList = ref<any>([])

// 获取评论列表
const getCommentList = async () => {
  commentList.value = await getGoodsCommentListAPI(route.params.id)
  console.log('评论列表：', commentList.value)
}
onMounted(() => getCommentList())

// 评论表单
const commentForm = reactive({
  rating: 0,
  content: '',
  images: '',
  productId: 0
})

const action = baseURL + '/api/upload'

// upload-file
const fileList = ref([])

// 评论图片上传列表
const uploadImgList: string[] = []

// 图片上传回调
const handleUploadImgSuccess = (res: any) => {
  uploadImgList.push(res.response?.data.url)
}

// 评论重置
const handleCommentReset = () => {
  commentForm.rating = 0
  commentForm.images = ''
  commentForm.content = ''
  commentForm.productId = 0
  fileList.value = []
}

// 评论提交
const handleCommentSubmit = async () => {
  if (!isLogin.value) {
    Message.error('请先登录！')
    isAuthDialogShow.value = true
    return
  }
  commentForm.productId = +route.params.id
  commentForm.images = uploadImgList.join(',')
  // 上传
  await postGoodsCommentAPI(commentForm)
  getCommentList()
  Message.success('发表评论成功！')
  handleCommentReset()
}

// 控制写评论区域显示隐藏
const isShowWriteCommentArea = ref(false)

const { addressList, isAdressModalShow } = storeToRefs(useAddressStore())
const { getCartList } = useCartStore()

// 是否选择过地址
const isSelectedAddress = computed(() => addressList.value.length)
// 第一个地址
const defaultAddress = computed(
  () =>
    addressList.value[0].province +
    addressList.value[0].city +
    addressList.value[0].district +
    addressList.value[0].address
)

const { isLogin, isAuthDialogShow } = storeToRefs(useAuthStore())

// 数量
const goodsNum = ref(1)
// 加入购物车
const handleJoinCart = async () => {
  if (!isLogin.value) {
    Message.error('请先登录！')
    isAuthDialogShow.value = true
    return
  }

  console.log(goods.value)
  const res = await addShoppingCartAPI({
    ...goods.value,
    goodsNum: goodsNum.value,
    checked: false
  })

  getCartList()
  Message.success('加入购物袋成功！')
}

const router = useRouter()
// 立即购买
const handleBuy = async () => {
  if (!isLogin.value) {
    Message.error('请先登录！')
    isAuthDialogShow.value = true
    return
  }

  const res = await addShoppingCartAPI({
    ...goods.value,
    goodsNum: goodsNum.value,
    checked: false
  })

  getCartList()

  router.push('/bags')
}

const handleSetAddress = () => {
  if (!isLogin.value) {
    Message.error('请先登录！')
    isAuthDialogShow.value = true
    return
  }
  isAdressModalShow.value = true
}
</script>

<template>
  <div class="w-1280px mx-auto pb-10">
    <a-space direction="vertical">
      <a-breadcrumb :routes="routes">
        <template #item-render="{ route, paths }">
          <router-link :to="{ path: route.path }">{{ route.label }}</router-link>
        </template>
      </a-breadcrumb>
    </a-space>
    <!-- 商品购买区域 -->
    <div class="min-h-500px my-5 flex gap-30">
      <!-- 放大镜组件区域 -->
      <div>
        <GoodsMagnifier :imgList />
      </div>

      <!-- 购买区 -->
      <div class="flex flex-col px-10 mt-4">
        <h3 class="text-2xl">{{ goods.name }}</h3>
        <p class="lh-normal text-gray-500 mt-4">
          {{ goods.description }}
        </p>
        <p class="flex justify-between items-end mt-8">
          <span class="text-red-7 text-3xl">¥ {{ goods.price }}</span>
          <span class="decoration-underline cursor-pointer">查看详情</span>
        </p>
        <div class="mt-4">
          <span>配送至：</span>
          <span v-if="isSelectedAddress">{{ defaultAddress }}</span>
          <span v-else @click="handleSetAddress" class="text-gray-7 decoration-underline cursor-pointer">
            去设置地址
          </span>
        </div>

        <div class="flex justify-between mt-10">
          <a-checkbox-group :default-value="[1]">
            <template v-for="item in 1" :key="item">
              <a-checkbox :value="item">
                <template #checkbox="{ checked }">
                  <a-space align="start" :class="{ 'custom-checkbox-card-checked': checked }">
                    <div className="custom-checkbox-card-mask">
                      <div className="custom-checkbox-card-mask-dot" />
                    </div>
                  </a-space>
                </template>
                <span class="select-none text-primary">专属刻字</span>
              </a-checkbox>
            </template>
          </a-checkbox-group>

          <span class="decoration-underline cursor-pointer">了解更多</span>
        </div>

        <div class="flex justify-between gap-4 mt-12">
          <div class="w-180px">
            <a-input-number
              class="w-full h-48px"
              placeholder="Please Enter"
              size="large"
              v-model="goodsNum"
              :default-value="1"
              :min="1"
              :max="goods.stock"
              mode="button"
            />
          </div>

          <div class="flex-1 flex h-full items-center">
            <a-button
              @click="handleJoinCart"
              class="rounded-none flex-1 h-full bg-white! border-primary! text-16px hover:bg-primary! hover:color-white!"
            >
              加入购物车
            </a-button>
            <a-button @click="handleBuy" class="rounded-none flex-1 h-full bg-primary! text-white! text-16px"
              >去购物车结算</a-button
            >
          </div>
        </div>
      </div>
    </div>
    <!-- 参数 -->
    <div class="flex gap-25 items-start">
      <div class="flex-1">
        <!-- 参数详情区域 -->
        <!-- <div class="bg-#f9f9f9 p-10">
          <h3 class="text-3xl">更多信息</h3>
          <div class="mt-4 h-50 grid grid-cols-2 text-4">
            <div class="flex">
              <div class="bg-light-blue-200 w-130px p-4 flex-shrink-0 flex items-center">类别</div>
              <div class="flex items-center pl-4 bg-white text-gray-600 w-full h-full">无暇底妆</div>
            </div>
            <div class="flex">
              <div class="bg-light-blue-200 w-130px p-4 flex-shrink-0 flex items-center">产品名称</div>
              <div class="flex items-center pl-4 bg-white text-gray-600 w-full h-full">三色遮瑕盘</div>
            </div>
            <div class="flex">
              <div class="bg-light-blue-200 w-130px p-4 flex-shrink-0 flex items-center">主要价格</div>
              <div class="flex items-center pl-4 bg-white text-gray-600 w-full h-full">169元/支</div>
            </div>
            <div class="flex">
              <div class="bg-light-blue-200 w-130px p-4 flex-shrink-0 flex items-center">销售分层</div>
              <div class="flex items-center pl-4 bg-white text-gray-600 w-full h-full">利润款</div>
            </div>
            <div class="flex">
              <div class="bg-light-blue-200 w-130px p-4 flex-shrink-0 flex items-center">细分</div>
              <div class="flex items-center pl-4 bg-white text-gray-600 w-full h-full">利润款</div>
            </div>
            <div class="flex items-center">
              <div class="bg-light-blue-200 w-130px h-full p-4 flex-shrink-0 flex items-center">标签</div>
              <div class="flex items-center pl-4 bg-white text-gray-600 w-full h-full">
                柔润肌肤、保湿舒缓、使底妆细腻服帖
              </div>
            </div>
          </div>
        </div> -->
        <!-- 海报区域 -->
        <div class="flex flex-col items-center mt-4">
          <div class="w-full" v-for="item in posterList" :key="item">
            <img class="w-full" :src="item" alt="" />
          </div>
        </div>
        <!-- 评论区域 -->
        <div class="bg-#f9f9f9 p-10 my-5">
          <div class="text-3xl flex items-center h-18 justify-between pb-6 border-b border-b-gray-3 border-b-solid">
            <h3 class="">商品评论区</h3>
            <a-button
              @click="isShowWriteCommentArea = true"
              class="rounded-none h-full bg-white! border-primary! px-10 text-16px hover:bg-primary! hover:color-white!"
            >
              添加您的评论
            </a-button>
          </div>

          <div class="py-8 text-4">
            <p v-if="!commentList.length">该产品尚未有评论，你是第一个写评论的人。</p>
            <div v-else class="bg-white p-3">
              <a-comment
                v-for="comment in commentList"
                :author="JSON.parse(comment.user).username"
                :datetime="new Date(comment.createdAt).toLocaleDateString().replace(/\//g, '-')"
                align="right"
              >
                <template #avatar>
                  <a-avatar class="w-60px h-60px mt-3">
                    <img alt="avatar" :src="baseURL + JSON.parse(comment.user).avatar" />
                  </a-avatar>
                </template>
                <template #content>
                  <a-rate readonly :default-value="comment.rating" />
                  <p class="text-4 my-2">
                    {{ comment.content }}
                  </p>
                  <!-- 图片 -->
                  <div class="flex gap-2" v-if="comment.images != ''">
                    <a-image v-for="url in comment.images.split(',')" width="100" :src="baseURL + url" />
                  </div>
                </template>
              </a-comment>
            </div>
          </div>

          <div class="overflow-hidden">
            <Transition>
              <div v-show="isShowWriteCommentArea" class="border-t border-t-gray-3 border-t-solid">
                <p class="py-8 text-2xl">发表评论</p>
                <div class="flex justify-between">
                  <div class="flex flex-col gap-4 w-full">
                    <div class="flex items-center">
                      <p class="text-lg w-30">总体评价：</p>
                      <a-rate v-model="commentForm.rating" />
                    </div>
                    <!-- 标签 -->
                    <!-- <div class="flex items-center">
                      <p class="text-lg w-30">标签：</p>
                      <GoodsCommentLabel />
                    </div> -->

                    <div class="flex flex-col gap-2">
                      <p class="text-lg w-30">评论：</p>
                      <a-textarea
                        v-model="commentForm.content"
                        class="bg-white! border-gray-2! h-40"
                        placeholder="请留下您的评论"
                        :max-length="{ length: 200, errorOnly: true }"
                        allow-clear
                        show-word-limit
                      />
                    </div>
                    <div>
                      <p class="text-lg w-30">上传图片：</p>
                      <!-- 上传图片组件 -->
                      <!-- TODO:上传图片 -->
                      <div class="mt-4">
                        <a-upload
                          v-model:file-list="fileList"
                          :limit="3"
                          list-type="picture-card"
                          :action="action"
                          image-preview
                          @success="handleUploadImgSuccess"
                        />
                      </div>
                    </div>
                    <!-- 提交 -->
                    <div class="flex justify-center items-center gap-24 mt-10 w-full">
                      <a-button
                        @click="handleCommentSubmit"
                        class="w-40 py-5 text-4 bg-#76a5af! opacity-85! hover:opacity-100! color-white!"
                        >提交</a-button
                      >
                      <a-button
                        @click="handleCommentReset"
                        class="bg-gray-7! opacity-85! hover:opacity-100! color-white! text-4 w-40 py-5"
                        >重置</a-button
                      >
                    </div>
                  </div>
                </div>
              </div>
            </Transition>
          </div>
        </div>
      </div>
      <!-- 你可能喜欢区域 ? -->
      <div class="w-300px p-4 text-xl border border-solid border-gray-3">
        <h3 class="text-center bg-#f7f7f7 py-4 flex items-center justify-center">
          <span>你可能喜欢</span>
          <div @click="handleRefreshRecommendList" class="p-1 hover:color-gray-8 color-gray-5 cursor-pointer">
            <icon-sync class="transition-all transition-delay-100" />
          </div>
        </h3>
        <div class="flex flex-col gap-2.5 py-6">
          <GoodsItem v-for="goods in recommendList" :key="goods.id" :goods />
        </div>
      </div>
    </div>
  </div>

  <AddressDialog />
</template>

<style lang="scss" scoped>
:root {
  --main-color: #76a5af;
}
.custom-checkbox-card-mask {
  height: 14px;
  width: 14px;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  border-radius: 2px;
  border: 1px solid #76a5af;
  box-sizing: border-box;
}

.custom-checkbox-card-mask-dot {
  width: 8px;
  height: 8px;
  border-radius: 2px;
}

.custom-checkbox-card-title {
  color: #76a5af;
  font-size: 14px;
  font-weight: bold;
  margin-bottom: 8px;
}

.custom-checkbox-card:hover,
.custom-checkbox-card-checked,
.custom-checkbox-card:hover .custom-checkbox-card-mask,
.custom-checkbox-card-checked .custom-checkbox-card-mask {
  border-color: #76a5af;
}

.custom-checkbox-card-checked {
  background-color: var(--color-primary-light-1);
}

.custom-checkbox-card:hover .custom-checkbox-card-title,
.custom-checkbox-card-checked .custom-checkbox-card-title {
  color: #76a5af;
}

.custom-checkbox-card-checked .custom-checkbox-card-mask-dot {
  background-color: #76a5af;
}

// 数字输入框
:deep(.arco-input-wrapper) {
  background-color: #fff;
  border-color: rgba(0, 0, 0, 0.1);
}

:deep(.arco-input-wrapper.arco-input-focus) {
  background-color: #fff;
  border-color: rgb(118, 165, 175, 0.7);
}

:deep(.arco-input) {
  text-align: center;
  font-size: 16px;
}

:deep(.text-left .arco-input) {
  text-align: left;
}

// 文本域focus样式
:deep(.arco-textarea-focus) {
  border-color: #66afe9 !important;
}

// 照片墙样式
:deep(.arco-upload-picture-card) {
  width: 150px;
  height: 150px;
}

.v-enter-active,
.v-leave-active {
  transition: all 0.3s ease;
}

.v-enter-from {
  transform: translateY(-100%);
}

.v-leave-to {
  transform: translateY(-100%);
}

:deep(.arco-input-wrapper) {
  background-color: white;
}

:deep(.arco-input-wrapper) {
  border-color: #ddd;
}

:deep(.arco-input-wrapper:hover) {
  background-color: #fff;
  border-color: #76a5af;
}

:deep(.arco-input-wrapper.arco-input-focus) {
  border-color: #76a5af;
}

:deep(.arco-input-search .arco-input-suffix) {
  font-size: 20px;
}

:deep(.arco-form-item-label-col) {
  width: 100px;
}

:deep(.arco-form-item-label) {
  width: 100px;
}

:deep(.arco-select-view-single) {
  background-color: white;
  border-color: #ddd;
}

:deep(.arco-select-view-focus) {
  border-color: #76a5af;
}

:deep(.arco-upload-list-picture) {
  width: 150px;
  height: 150px;
}

:deep(.arco-upload-icon) {
  font-size: 30px;
}

:deep(.arco-upload-list-picture-mask) {
  line-height: 150px;
}

:deep(.arco-icon-star-fill) {
  font-size: 18px;
}
</style>
